package com.alongthink.javademo.queue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class CustomerFSY implements Runnable {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     *         抛出异常    特殊值        阻塞         超时
     插入    add(e)    offer(e)    put(e)    offer(e, time, unit)
     移除    remove()    poll()    take()    poll(time, unit)
     检查    element()    peek()    不可用    不可用
     */
    private BlockingQueue blockingQueue;
    private AtomicInteger count = new AtomicInteger();
    public CustomerFSY(BlockingQueue blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p/>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        logger.info("消费者线程启动...");
//        LockFlag.setCustomerRunningFlag(true);
        try {
            while (LockFlag.getCustomerRunningFlag()){
                if(null!=blockingQueue && blockingQueue.size() > 0) {
                    Object o = blockingQueue.poll(3, TimeUnit.MILLISECONDS);
                    if (o != null) {
                        //处理数据
                        Thread.sleep(10);
                    }
                }else {
                    LockFlag.setCustomerRunningFlag(false);
                }
            }
//            System.err.println("消费者程序执行完毕");
        } catch (InterruptedException e) {
            System.err.println("消费者程序退出");
            LockFlag.setCustomerRunningFlag(false);//异常退出线程
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
    }
}
